<template>
  <!-- 添加或修改产品信息表对话框 -->
  <el-dialog :title="title" v-model="props.open" width="800px" append-to-body style="min-height: 200px">
    <el-form ref="componentConfigRef" label-width="80px" :model="data">
      <el-row v-for="(domain, index) in domains" :key="index">
        <el-col :span="10">
          <el-form-item label="属性名称"  :prop="'domains.' + index + '.name'"
                        :rules="[{ required: true, message: '属性名称不能为空', trigger: 'blur' }]">
            <el-input v-model="domain.name" placeholder="请输入属性名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="属性值" :prop="'domains.' + index + '.value'"
                        :rules="{ required: true, message: '属性值不能为空', trigger: 'blur' }">
            <el-input v-model="domain.value" placeholder="请输入属性值"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button style="margin-left: 10px" @click.prevent="removeDomain(domain)">-</el-button>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button style="margin-right: 530px" type="success" @click="addDomain">新增项</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="ProtocolComponentConfigView">

const route = useRoute();
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const props = defineProps({
  // 数据
  open: {
    type: Boolean,
    default: false,
  },
  // 当未找到匹配的数据时，显示value
  componentId: {
    type: Number,
    default: 0,
  },
  config: {
    type: String,
    default: '',
  }
});

const title = ref("组件属性配置")


const data = reactive({
  domains: [{name:'',value:''}],
});

const { domains } = toRefs(data);

onMounted(() => {

})

watch(
  () => props.open,
  (newVal, oldVal) => {
    if (props.config) {
      domains.value = []
      let configObj = JSON.parse(props.config)
      for (let key in configObj) {
        domains.value.push({
          name: key,
          value: configObj[key],
        })
      }
    } else {
      reset()
    }
  }
)

const removeDomain = (item) => {
  const index = domains.value.indexOf(item)
  if (index !== -1) {
    domains.value.splice(index, 1)
  }
}

const addDomain = () => {
  domains.value.push({
    name: '',
    value: '',
  })
}

function submitForm(){
  proxy.$refs["componentConfigRef"].validate(valid => {
    if (valid) {
      let result = {}
      domains.value.forEach(item=>{
        result[item.name] = item.value
      })
      emit('setConfig',JSON.stringify(result))
    }
  })

  //emit('closeConfig')
}
function reset(){
  domains.value = [{
    name: '',
    value: '',
  }]
}
function cancel(){
  reset()
  emit('closeConfig')
}

</script>


<style scoped lang="scss">

</style>